<?php

namespace app\admin\controller;

use app\admin\model\ProjectYearSwitch;
use app\common\controller\Backend;
use app\admin\model\Fields;
use app\admin\model\Admin;
use app\admin\model\AdminProject;
use think\Db;
use fast\Random;
use app\admin\library\Time;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Highproject extends Backend
{
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->whereExtend['is_important'] = 1;
        $this->whereExtend['library_id'] = 2;
        $this -> year = $this -> request -> get('year',date('Y'));
        $this->model = new \app\admin\model\Project([],$this -> year);

        $chargedep =  getSelectList("chargedep");
        $this->assign('chargedep',$chargedep);

        $street = getSelectList("chargedep",['group_id'=>5]);
        $this->assign('street',$street);

        $five_industry =[''=>'请选择'] + getSelectList("five_industry");
        $this->assign('five_industry',$five_industry);

        $industry_category = getSelectList("industry_category");
        $this->assign('industry_category',$industry_category);

        $project_source = getSelectList("activity");
        $this->assign('project_source',$project_source);

        $carrier = [''=>'请选择'] + getSelectList("carrier");
        $this->assign('carrier',$carrier);

        $investor_attribute = getSelectList("investor_attribute");
        $this->assign('investor_attribute',$investor_attribute);
    }

    public function add() {

        $field_where['table_name'] = 'project';
        $field_where['status'] = 1;
        $field_where['item_library'] = ['in',"0,2"];
        // $field_where['item_action'] = ['in',"0,1"];
        // $field_where['item_admin'] = ['in',"0,1"];
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $data['pno'] = Random::uuid();
                $data['library_id'] = SIGNED;
                $data['status'] = 1;
                $data['name'] = $params['name'];
                $data['is_important'] = 1;
                $exist_row = $this->model->where(['name'=>$data['name']])->find();
                if($exist_row)
                    $this->error(__('此项目已存在'));

                $data['library_name'] = '签约库';

                // pr($params);
                // pr(collection($fields_list)->toArray());
                foreach ($fields_list as $key => $value) {

                    $field = $value['item_id'];

                    $data['status'] = 0;


                    // if(!isset($params[$field]))
                    //     continue;
                    if($params[$field] == '待定'){
                        $params[$field] = PENDING;
                    }
                    // pr($params[$field]);
                    if(is_array($params[$field]))
                    {
                        $params[$field] = implode(",",$params[$field]);

                    }

                    // pr($params);
                    if(isset($params[$field]) && $params[$field])
                    {
                        $data[$field] = $params[$field];



                        if($value['item_type'] == "select")
                        {
                            // echo "Aaaa";
                            $rule = json_decode($value['item_rule'], true);
                            $name_field = str_replace('id','name', $field);
                            if(is_string($rule['datasource'])){
                                $tb_name = $rule['datasource'];
                                $data[$name_field] =  getSelectText($tb_name,$params[$field]);
                            }else
                                $data[$name_field] = $rule['datasource'][$params[$field]];
                        }

                        if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                        {
                            if($params[$field] == PENDING)
                                $data[$field.'_desc'] = '待定';
                            else
                                $data[$field.'_desc'] = $params[$field];
                            // $data_params['value'] = $data_params['value'];
                        }
                    }
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // $result = $this->model->allowField(true)->save($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    // $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        // pr(collection($list)->toArray());
        return $this->view->fetch();
    }

    public function edit($ids = null) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $field_where['table_name'] = 'project';
        $field_where['status'] = 1;
        $field_where['item_library'] = ['in',"0,2"];
        // $field_where['item_action'] = ['in',"0,1"];
        // $field_where['item_admin'] = ['in',"0,1"];
        $fields_list = Fields::where($field_where)->order('weight','asc')->select();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // pr(collection($fields_list)->toArray());
                foreach ($fields_list as $key => $value) {

                    $field = $value['item_id'];

                    $data['status'] = 0;


                    // if(!isset($params[$field]))
                    //     continue;
                    if($params[$field] == '待定'){
                        $params[$field] = PENDING;
                    }
                    // pr($params[$field]);
                    if(is_array($params[$field]))
                    {
                        $params[$field] = implode(",",$params[$field]);

                    }

                    // pr($params);
                    if(isset($params[$field]) && $params[$field])
                    {
                        $data[$field] = $params[$field];

                        if($value['item_type'] == "select")
                        {
                            // echo "Aaaa";
                            $rule = json_decode($value['item_rule'], true);
                            $name_field = str_replace('id','name', $field);
                            if(is_string($rule['datasource'])){
                                $tb_name = $rule['datasource'];
                                $data[$name_field] =  getSelectText($tb_name,$params[$field]);
                            }else
                                $data[$name_field] = $rule['datasource'][$params[$field]];
                        }

                        if($value['item_type'] == "datetime" || $value['item_type'] == "date")
                        {
                            if($params[$field] == PENDING)
                                $data[$field.'_desc'] = '待定';
                            else
                                $data[$field.'_desc'] = $params[$field];
                            // $data_params['value'] = $data_params['value'];
                        }
                    }
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    // $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}